package com.ly.bean.spring;

import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.Test;

import com.ly.Annotation.Controller;
import com.ly.Annotation.RequestMapping;

/**
 * 加载所有controller 下面的对应所有methods
 * @author admin
 *
 */
public class BeanFactory {
	
	List<String> classPaths = new ArrayList<String>();
	Map<String, List<String>> controRequMap = new HashMap<String, List<String>>();//controller与requestMapping的映射关系集合

	public BeanFactory() {
	}
	
	public  Map<String, List<String>> getAction() throws Exception {
		// 包名
		String backage = "com.ly.action";
		String classpath = BeanFactory.class.getResource("/").getPath();
		classpath = java.net.URLDecoder.decode(classpath,"utf-8");  //路径出来要转换成UTF—8格式
		classpath = classpath.substring(1, classpath.length());
		// 然后把我们的包名basPach转换为路径名
		backage = backage.replace(".", "/");
		String backagePath = (classpath + backage);
		File file = new File(backagePath);
		this.doPath(file);
		for (String s : classPaths) {
			// 将E:\myCompany\AnnotationWeb\WebRoot\WEB-INF\classes\com\ly\action\AnnoServlet.class这样路径替换成类的全类名com.ly.action.annoAction
			s = s.replace(classpath.replace("/", "\\"), "").replace("\\", ".")
					.replace(".class", "");
			this.getMethodAnno(s);
		}
		System.out.println("controRequMap:"+controRequMap);
		return controRequMap;

	}

	/**
	 * 添加文件夹下的路径
	 * 
	 * @param file
	 */
	public void doPath(File file) {
		if (file.isDirectory()) {// 文件夹
			// 文件夹我们就递归
			File[] files = file.listFiles();
			for (File f1 : files) {
				doPath(f1);
			}
		} else {// 标准文件
			int i = 1;
			// 标准文件我们就判断是否是class文件
			if (file.getName().endsWith(".class")) {
				// 如果是class文件我们就放入我们的集合中。
				classPaths.add(file.getPath());
			}
		}

	}

	public void getMethodAnno(String controlPath) throws ClassNotFoundException {
		List<String> requMappNameList = new ArrayList<String>();
		Class clazz = Class.forName(controlPath);
		if (clazz.isAnnotationPresent(Controller.class)) {
			Controller controlAnno = (Controller) clazz
					.getAnnotation(Controller.class);
			String controlName = controlAnno.value();
			Method[] methods = clazz.getMethods();
			for (Method method : methods) {
				if (method.isAnnotationPresent(RequestMapping.class)) {
					RequestMapping requMappAnno = (RequestMapping) method
							.getAnnotation(RequestMapping.class);
					String requMappName = requMappAnno.value();
					requMappNameList.add(requMappName);
				}
			}
			controRequMap.put(controlPath, requMappNameList);
		}
		;
	}
	public static void main(String[] args) throws Exception {
		BeanFactory fact = new BeanFactory();
		 Map<String,List<String>> map=fact.getAction();
	
	}
}
